package com.ivo.web;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 *@author wangjian
 *@time 2018年3月14日 - 上午10:02:12
 *@description:
 */
public class LoginFilter implements Filter {

	/**
	 * 排除拦截
	 */
	protected List<String> excludeList = null;
	private PathMatcher pathMatcher = null;

	/**
	 *存储的Session属性名
	 */
	String login_user = "LOGIN_USER";

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String excludes = filterConfig.getInitParameter("excludes");
		excludeList = Arrays.asList(excludes.split(","));
		pathMatcher = new AntPathMatcher();
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		if (matchExcludePath(request.getServletPath())) {
			chain.doFilter(servletRequest, servletResponse);
		} else {
			HttpServletResponse response = (HttpServletResponse) servletResponse;
			HttpSession session = request.getSession();
			if(session.getAttribute(login_user)==null){
				response.sendRedirect("login");
			}else{
				chain.doFilter(request, response);
			}
		}
	}

	private boolean matchExcludePath(String path) {
		if (excludeList != null) {
			for (String ignore : excludeList) {
				if (pathMatcher.match(ignore, path)) {
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public void destroy() {

	}
}
